package gold.digger;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/3/1.
 */
public class LC54 {

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        int k = 0, m = matrix.length;
        if (null == matrix || m <= 0) {
            return res;
        }
        int n = matrix[0].length;
        int limit = Math.min(m % 2 == 0 ? m / 2 : m / 2 + 1, n % 2 == 0 ? n / 2 : n / 2 + 1) - 1;

//        while ((k <= m - 1) && (k <= n - 1) && ((k <= n - 1 - k) || (k <= m - 1 - k) || (n - 2 - k >= k) || (m - 2 - k >= k + 1))) {
        while (k <= limit) {
            // loop 1

            for (int i = k; i <= n - 1 - k; ++i) {
                res.add(matrix[k][i]);
            }
            // loop 2
            for (int i = k + 1; i <= m - 1 - k; ++i) {
                res.add(matrix[i][n - 1 - k]);
            }
            // loop 3
            for (int i = n - 2 - k; i >= k && m - 1 - k > k; --i) {
                res.add(matrix[m - 1 - k][i]);
            }
            // loop 4
            for (int i = m - 2 - k; i >= k + 1 && k < n - 1 - k; --i) {
                res.add(matrix[i][k]);
            }
            k++;
        }

        return res;
    }


    public static void main(String[] args) {
        LC54 an = new LC54();
        int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
//        int[][] arr = {{1, 2, 3, 4}};
//        int[][] arr = {{2, 5, 8}, {4, 0, -1}};

        System.out.println(an.spiralOrder(arr));
    }
}

